#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define XMODEM_PACKET_SIZE 128  
#define XMODEM_SOH 0x01  
#define XMODEM_EOT 0x04  
#define XMODEM_ACK 0x06  
#define XMODEM_NAK 0x15  
#define XMODEM_CAN 0x18 

typedef struct
{
	char header;                   
	char packet_number;             
	char packet_number_c;            
	char data[128];   
	char check;                 
} xmodem_packet_t;

char check_sum(char *data, int len)
{
	char sum = 0;
	for(int i = 0; i < len; i++)
	{
		sum += data[i];
	}
	return sum;
}

void send_xmodem_packet(xmodem_packet_t *pXmod, size_t packet_number, size_t packet_remain)
{
	char send_buf[132];
	pXmod->packet_number = packet_number;
	pXmod->packet_number_c = ~packet_number;
	
	
	if(packet_remain != 0)
		memset(pXmod->data + packet_remain,0x1a,XMODEM_PACKET_SIZE - packet_remain);
	
	pXmod->check = check_sum(pXmod->data, XMODEM_PACKET_SIZE);
	
	*send_buf = pXmod->header; 
	*(send_buf + 1) = pXmod->packet_number; 
	*(send_buf + 2) = pXmod->packet_number_c; 
	memcpy(send_buf + 3,pXmod->data,XMODEM_PACKET_SIZE);
	*(send_buf + XMODEM_PACKET_SIZE + 3) = pXmod->check; 
	
	for(int i=0;i< 132;i++){
		printf("%02x ",send_buf[i]);
	}
	printf("\n");
	
}

char a[2][3] = {{0x0a,0x00,0x1a},{0x0b,0x00,0x1b}};		//test data
				

int main()
{
	xmodem_packet_t *pXmod;
	pXmod = malloc(sizeof(xmodem_packet_t));
	
	FILE *file;
	pXmod->header = XMODEM_SOH;
	
	file = fopen("DEMO3.bin","rb");
	char data[XMODEM_PACKET_SIZE];
	int size,packet = 0;

	while(!feof(file)){
		
		packet++;
		fseek(file,0,SEEK_CUR);
		size = fread(data,1,XMODEM_PACKET_SIZE,file);
		memcpy(pXmod->data,data,size);
		send_xmodem_packet(pXmod,packet,size);
	}
	
	
	free(pXmod);
	
	return 0;
}


